import { Component, createTextVNode } from "inferno";
import classnames from "classnames";
import "KaiUI/src/components/TextInput/TextInput.scss";
import morecolor from "../morecolor.scss";

const prefixCls = "kai-text-input";
const labelCls = `${prefixCls}-label p-thi`;
const inputCls = `${prefixCls}-label p-pri`;

class TextInput extends Component {
  constructor(props) {
    const {
      id,
      focusClass,
      label,
      index,
      onFocusChange,
      forwardedRef,
      onChange,
      enableTabSwitching,
      initialValue,
      placeholder,
      fieldType,
      validationError,
      defaultValue,
    } = props;
    super(props);
    this.onChange = (evt) => {
      this.setState({ value: evt.target.value });
      if (onChange) onChange(evt);
    };
    this.label = label;
    this.placeholder = placeholder;
    this.fieldType = fieldType || "text";
    this.focusClass = focusClass;

    this.state = {
      id: id,
      index: index,
      onFocusChange: onFocusChange,
      enableTabSwitching: enableTabSwitching,
      initialValue: initialValue,
      validationError: validationError,
      forwardedRef: forwardedRef,
      value: defaultValue || "",
    };
  }

  componentDidUpdate() {
    if (this.props.isFocused) this.textInput.focus();
  }

  render() {
    const errorCls = this.state.validationError ? `${prefixCls}-error` : "";
    const itemCls = classnames([
      prefixCls,
      this.props.isFocused && `${prefixCls}--focused ${this.focusClass || ""}`,
      errorCls,
    ]);

    return (
      <div
        id={this.state.id}
        tabIndex={0}
        className={itemCls}
        style={`background-color: ${
          this.props.isFocused ? morecolor.item_bg_focus_color : ""
        }`}
        key={this.props.isFocused}
      >
        <label className={labelCls} $HasVNodeChildren>
          {createTextVNode(
            this.state.validationError ? this.state.validationError : this.label
          )}
        </label>
        <input
          onKeyDown={this.onChange}
          type={this.fieldType}
          className={inputCls}
          defaultValue={this.state.value || ""}
          placeholder={this.placeholder || ""}
          style={`color: ${this.props.isFocused ? "var(--text-color)" : ""}`}
          ref={(input) => {
            this.textInput = input;
          }}
        />
      </div>
    );
  }
}

export default TextInput;
